package com.example.dessert.util.interceptor;

import com.example.dessert.annotation.LoginCheck;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * @ClassName: LoginInterceptor
 * @Description: 登录拦截器（拦截器方式）
 * @Author li
 * @Date 2022/1/11
 * @Version 1.0
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 判断用户是否登录
        if (this.hasPermission(request, handler)) {
            return true;
        }

        // 没有登录跳转到登录界面
        response.sendRedirect("/fore/login");

        return false;
    }


    /**
     * 判断权限
     *
     */
    private boolean hasPermission(HttpServletRequest request, Object handler) {

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //获取方法上的注解
            LoginCheck loginCheck = handlerMethod.getMethod().getAnnotation(LoginCheck.class);

            //方法未被注解修饰，则不验证
            if (loginCheck == null) {
                return true;
            }

            //判断用户是否登录
            Object userId = request.getSession().getAttribute("userId");
            return userId != null;

        }
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


}
